import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:wallet_flutter_module/k_line_chart/utils/date_format_util.dart';
import 'package:wallet_flutter_module/k_line_chart/utils/time_bean.dart';

import 'k_line_chart/entity/k_line_entity.dart';
import 'k_line_chart/k_chart_widget.dart';
import 'k_line_chart/utils/data_util.dart';
import 'k_line_chart/utils/event_tag_name.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';

import 'k_line_chart/utils/k_line_drop_down_header.dart';
import 'k_line_chart/utils/kline_rule_bean.dart';

class KLineChartPanel extends StatefulWidget {
  @override
  _KLineChartPanelState createState() => _KLineChartPanelState();
}

class _KLineChartPanelState extends State<KLineChartPanel>
    with WidgetsBindingObserver {
  List<String> _dropDownHeaderItemStrings = ['时间', '指标'];

  int _selectTimePosition = 0;

  List<TimeBean> _timeList = [];

  //主图
  List<KLineRuleBean> _KLineRuleMainList = [];

  int _selectKLineRuleMainPosition = -10;

  bool _showKLineRuleMain = true;

  var dropDownMainHeight = 100.0;

  //副图
  List<KLineRuleBean> _KLineRuleFuList = [];

  int _selectKLineRuleFuPosition = -10;

  bool _showKLineRuleFueMain = true;

  var dropDownFuHeight = 100.0;

  var screenWidth = 0.0;

  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  _buildTimeWidget(void itemOnTap(String selectValue)) {
    var mSpacing = 4.0;

    var crossAxisCount = 4;

    var paddingVertical = 3.0;

    var paddingHorizontal = 4.0;

    var mItemCount = _timeList.length;

    var cellWidth = (screenWidth - paddingHorizontal) / crossAxisCount;

    var refer = mItemCount / crossAxisCount;

    var rowCount = mItemCount % crossAxisCount == 0 ? refer : refer + 1;

    var cellHeight = (dropDownMainHeight - paddingVertical) / rowCount;

    var mChildAspectRatio = cellWidth / cellHeight;

    return Container(
      color: ColorUtil.color('#F2F2F2'),
      padding: EdgeInsets.symmetric(
          vertical: paddingVertical, horizontal: paddingHorizontal),
      child: GridView.builder(
        //注意
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(

            //水平子 Widget 之间间距
            crossAxisSpacing: mSpacing,

            //垂直子 Widget 之间间距
            mainAxisSpacing: mSpacing,

            //一行的 Widget 数量
            crossAxisCount: crossAxisCount,
            childAspectRatio: mChildAspectRatio),
        itemCount: mItemCount,
        itemBuilder: (context, index) => GestureDetector(
          onTap: () {
            _selectTimePosition = index;
            itemOnTap(_timeList[index].title);
            isLine = _timeList[index].isLine;
            showLoading = true;
            setState(() {});
            _requireNativeData();
          },
          child: Container(
            child: Stack(
              alignment: Alignment.center,
              children: [
                Text(
                  _timeList[index].title,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 10),
                ),
                Positioned(
                    right: 0,
                    top: 0,
                    child: index == _selectTimePosition
                        ? SizedBox(
                            width: 12,
                            height: 12,
                            child: Image.asset('img/quotes_selected.png'),
                          )
                        : SizedBox())
              ],
            ),
            decoration: BoxDecoration(
                color: index == _selectTimePosition
                    ? Colors.white
                    : Colors.transparent,
                borderRadius: BorderRadius.circular(2.0),
                border: Border.all(
                  color: index == _selectTimePosition
                      ? Colors.blue
                      : Colors.transparent,
                  width: 0.5,
                )),
          ),
        ),
      ),
    );
  }

  Widget _loadKLinePanel() {
    if (showLoading)
      return Container(
          width: double.infinity,
          alignment: Alignment.center,
          child: CircularProgressIndicator());
    else if (datas.isNotEmpty)
      return Stack(children: [
        Container(
          margin: EdgeInsets.symmetric(horizontal: 4),
          width: double.infinity,
          child: KChartWidget(
            datas,
            isLine: isLine,
            mainState: _mainState,
            secondaryState: _secondaryState,
            volState: VolState.VOL,
            fractionDigits: 4,
          ),
        )
      ]);
    else
      return Container(
        alignment: Alignment.center,
        width: double.infinity,
        child: FlatButton(
            onPressed: () {
              showLoading = true;
              _requireNativeData();
              setState(() {});
            },
            child: Text(
              "重新加载",
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.blue),
      );
  }

  _buildIndicatorsWidget(void itemOnTap(String selectValue)) {
    var childAspectRatio = 4.2;
    return Container(
      padding: EdgeInsets.symmetric(vertical: 3, horizontal: 4),
      color: ColorUtil.color('#F2F2F2'),
      child: ListView(
        shrinkWrap: true,
        children: [
          Column(
            children: [
              Row(
                children: [
                  Container(
                    width: 60,
                    alignment: Alignment.center,
                    child: Text(
                      '主图',
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  Expanded(
                      flex: 1,
                      child: Container(
                        child: GridView.builder(
                          shrinkWrap: true,
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(

                                  //水平子 Widget 之间间距
                                  crossAxisSpacing: 4,

                                  //垂直子 Widget 之间间距
                                  mainAxisSpacing: 4,

                                  //一行的 Widget 数量
                                  crossAxisCount: 2,
                                  childAspectRatio: childAspectRatio),
                          itemCount: _KLineRuleMainList.length,
                          itemBuilder: (context, index) => GestureDetector(
                            onTap: () {
                              _selectKLineRuleMainPosition = index;
                              _showKLineRuleMain = true;
                              itemOnTap(_KLineRuleMainList[index].title);
                              _mainState = MainState
                                  .values[_KLineRuleMainList[index].id];
                              setState(() {});
                            },
                            child: Container(
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  Text(
                                    _KLineRuleMainList[index].title,
                                    textAlign: TextAlign.center,
                                    style: TextStyle(fontSize: 10),
                                  ),
                                  Positioned(
                                      right: 0,
                                      top: 0,
                                      child:
                                          index == _selectKLineRuleMainPosition
                                              ? SizedBox(
                                                  width: 12,
                                                  height: 12,
                                                  child: Image.asset(
                                                      'img/quotes_selected.png'),
                                                )
                                              : SizedBox())
                                ],
                              ),
                              decoration: BoxDecoration(
                                  color: index == _selectKLineRuleMainPosition
                                      ? Colors.white
                                      : Colors.transparent,
                                  borderRadius: BorderRadius.circular(2.0),
                                  border: Border.all(
                                    color: index == _selectKLineRuleMainPosition
                                        ? Colors.blue
                                        : Colors.transparent,
                                    width: 0.5,
                                  )),
                            ),
                          ),
                        ),
                      )),
                  GestureDetector(
                    onTap: () => {
                      _selectKLineRuleMainPosition = -10,
                      _showKLineRuleMain = false,
                      _mainState = MainState.NONE,
                      setState(() {})
                    },
                    child: Container(
                      width: 60,
                      padding: EdgeInsets.symmetric(vertical: 4, horizontal: 4),
                      child: Icon(
                          _showKLineRuleMain
                              ? Icons.visibility
                              : Icons.visibility_off,
                          color: Colors.blue,
                          size: 18),
                    ),
                  ),
                ],
              ),
              Padding(padding: EdgeInsets.only(top: 4)),
              Row(
                children: [
                  Container(
                    width: 60,
                    alignment: Alignment.center,
                    child: Text(
                      '副图',
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  Expanded(
                      flex: 1,
                      child: Container(
                        child: GridView.builder(
                          shrinkWrap: true,
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(

                                  //水平子 Widget 之间间距
                                  crossAxisSpacing: 4.0,

                                  //垂直子 Widget 之间间距
                                  mainAxisSpacing: 4.0,

                                  //一行的 Widget 数量
                                  crossAxisCount: 2,
                                  childAspectRatio: childAspectRatio),
                          itemCount: _KLineRuleFuList.length,
                          itemBuilder: (context, index) => GestureDetector(
                            onTap: () {
                              _selectKLineRuleFuPosition = index;
                              _showKLineRuleFueMain = true;
                              itemOnTap(_KLineRuleFuList[index].title);
                              _secondaryState = SecondaryState
                                  .values[_KLineRuleFuList[index].id];
                              setState(() {});
                            },
                            child: Container(
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  Text(
                                    _KLineRuleFuList[index].title,
                                    textAlign: TextAlign.center,
                                    style: TextStyle(fontSize: 10),
                                  ),
                                  Positioned(
                                      right: 0,
                                      top: 0,
                                      child: index == _selectKLineRuleFuPosition
                                          ? SizedBox(
                                              width: 12,
                                              height: 12,
                                              child: Image.asset(
                                                  'img/quotes_selected.png'),
                                            )
                                          : SizedBox())
                                ],
                              ),
                              decoration: BoxDecoration(
                                  color: index == _selectKLineRuleFuPosition
                                      ? Colors.white
                                      : Colors.transparent,
                                  borderRadius: BorderRadius.circular(2.0),
                                  border: Border.all(
                                    color: index == _selectKLineRuleFuPosition
                                        ? Colors.blue
                                        : Colors.transparent,
                                    width: 0.5,
                                  )),
                            ),
                          ),
                        ),
                      )),
                  GestureDetector(
                    onTap: () => {
                      _selectKLineRuleFuPosition = -10,
                      _showKLineRuleFueMain = false,
                      _secondaryState = SecondaryState.NONE,
                      setState(() {})
                    },
                    child: Container(
                      width: 60,
                      padding: EdgeInsets.symmetric(vertical: 4, horizontal: 4),
                      child: Icon(
                          _showKLineRuleFueMain
                              ? Icons.visibility
                              : Icons.visibility_off,
                          color: Colors.blue,
                          size: 18),
                    ),
                  ),
                ],
              )
            ],
          )
        ],
      ),
    );
  }

  _onScreenOption() async {
    try {
      Map<String, Object> map = {"shareUrl": "https://www.baidu.com"};
      var result = await _channel.invokeMethod("screen_option_land", map);
      print(result);
    } catch (e) {
      print(e);
    }
  }

  List<KLineEntity> datas;
  bool showLoading = true;
  MainState _mainState = MainState.MA;
  SecondaryState _secondaryState = SecondaryState.MACD;
  bool isLine = true;

  static const EventChannel _eventChannelPlugin =
      EventChannel(KLine_Chart_Panel_Msg_Tag);

  static const _channel = const MethodChannel(FLUTTER_TO_NATIVE);

  // String showMessage = "flutter_view";
  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _getLocalData();

    if (_streamSubscription == null) {
      _streamSubscription = _eventChannelPlugin
          .receiveBroadcastStream('123')
          .listen(_onEvent, onError: _onError);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _requireNativeData();
    }
  }

  _getLocalData() async {
    //时间数据
    String result = await rootBundle.loadString('json_date/k_line_time');
    Map parseJson = json.decode(result);
    List list = parseJson['data'];
    _timeList = list
        .map((item) => TimeBean.fromJson(item))
        .toList()
        .toList()
        .cast<TimeBean>();

    _dropDownHeaderItemStrings[0] = _timeList[_selectTimePosition].title;

    //主图数据
    String mKLineRuleMainResult =
        await rootBundle.loadString('json_date/zhu_tu_rule');
    Map mKLineRuleMainParseJson = json.decode(mKLineRuleMainResult);
    List mKLineRuleMainList = mKLineRuleMainParseJson['data'];
    _KLineRuleMainList = mKLineRuleMainList
        .map((item) => KLineRuleBean.fromJson(item))
        .toList()
        .toList()
        .cast<KLineRuleBean>();

    //副图数据
    String mKLineRuleFuResult =
        await rootBundle.loadString('json_date/fu_tu_rule');
    Map mKLineRuleFuParseJson = json.decode(mKLineRuleFuResult);
    List mKLineRuleFuList = mKLineRuleFuParseJson['data'];
    _KLineRuleFuList = mKLineRuleFuList
        .map((item) => KLineRuleBean.fromJson(item))
        .toList()
        .toList()
        .cast<KLineRuleBean>();

    setState(() {});
  }

  void _requireNativeData() async {
    try {
      Map<String, Object> map = {
        "param": _timeList[_selectTimePosition].toJson().toString()
      };
      var result = await _channel.invokeMethod("requireNativeData", map);
      print("flutter_result=====$result");
    } catch (e) {
      print(e);
    }
  }

  _onError(error) {}

  void _onEvent(event) {
    // Map parseJson = json.decode(event.toString());
    // List list = parseJson['data'];
    List list = json.decode(event.toString());
    print('event: ${event.toString()}');
    datas = list
        .map((item) => KLineEntity.fromJson(item))
        .toList()
        .reversed
        .toList()
        .cast<KLineEntity>();
    DataUtil.calculate(datas);
    showLoading = false;
    setState(() {});
  }

  @override
  void dispose() {
    if (_streamSubscription != null) {
      _streamSubscription.cancel();
      _streamSubscription = null;
    }
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    screenWidth = mediaQuery.size.width;

    return Scaffold(
      extendBody: true,
      primary: false,
      body: Stack(
        key: _stackKey,
        children: [
          Column(
            children: [
              Row(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: 120,
                    color: Colors.white,
                    child: KLineDropDownHeader(
                      // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                      items: _dropDownHeaderItemStrings
                          .map((e) => GZXDropDownHeaderItem(e))
                          .toList(),
                      // GZXDropDownHeader对应第一父级Stack的key
                      stackKey: _stackKey,
                      // controller用于控制menu的显示或隐藏
                      controller: _dropdownMenuController,
                      // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
                      onItemTap: (index) {},
                      // 头部的高度
                      height: 32,
                      width: 120,
//                // 头部背景颜色
//                color: Colors.red,
//                // 头部边框宽度
                      borderWidth: 0,
//                // 头部边框颜色
//                borderColor: Color(0xFFeeede6),
//                // 分割线高度
                      dividerHeight: 0,

//                // 文字样式
                      style: TextStyle(color: Color(0xFF666666), fontSize: 10),
//                // 下拉时文字样式
                      dropDownStyle: TextStyle(
                        fontSize: 10,
                        color: Theme.of(context).primaryColor,
                      ),
//                // 图标大小
//                iconSize: 20,
//                // 图标颜色
//                iconColor: Color(0xFFafada7),
//                // 下拉时图标颜色
//                iconDropDownColor: Theme.of(context).primaryColor,
                    ),
                  ),
                  Expanded(
                      flex: 1,
                      child: Container(
                        height: 32,
                        color: Colors.white,
                        child: Stack(
                          alignment: Alignment.centerRight,
                          children: [
                            GestureDetector(
                              onTap: () => {_onScreenOption()},
                              child: Container(
                                width: 60,
                                child: Icon(
                                  Icons.fullscreen,
                                  color: Colors.blue,
                                  size: 24,
                                ),
                              ),
                            )
                          ],
                        ),
                      ))
                ],
              ),
              Divider(color: Colors.grey, height: 0.5),
              Expanded(
                child: _loadKLinePanel(),
              ),
            ],
          ),
          // 下拉菜单
          GZXDropDownMenu(
              // controller用于控制menu的显示或隐藏
              controller: _dropdownMenuController,
              // 下拉菜单显示或隐藏动画时长
              animationMilliseconds: 100,
              // 下拉后遮罩颜色
              maskColor: Colors.transparent,
              dropdownMenuChanging: (isShow, index) {},
              dropdownMenuChanged: (isShow, index) {},
              // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
              menus: [
                GZXDropdownMenuBuilder(
                    dropDownHeight: dropDownMainHeight,
                    dropDownWidget: _buildTimeWidget((selectValue) {
                      _dropDownHeaderItemStrings[0] = selectValue;
                      _dropdownMenuController.hide();
                      setState(() {});
                    })),
                GZXDropdownMenuBuilder(
                    dropDownHeight: dropDownFuHeight,
                    dropDownWidget: _buildIndicatorsWidget((selectValue) {
                      // _dropDownHeaderItemStrings[1] = selectValue;
                      _dropdownMenuController.hide();
                      setState(() {});
                    })),
              ])
        ],
      ),
    );
  }
}
